'''
Author: xialang333@gmail.com
Date: 2025-08-04 14:35:59
LastEditTime: 2025-08-04 16:51:06
'''
from fastapi import FastAPI, Depends
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles

import uvicorn
from config import settings
from app.database import Base, engine
from app import api, metrics, views
from app.metrics import router as metrics_router

# 创建数据库表
Base.metadata.create_all(bind=engine)

app = FastAPI(
    title=settings.title,
    description=settings.description,
    version=settings.version
)

# 中间件配置
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # 生产环境应该限制为具体的域名
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 挂载静态文件
app.mount("/static", StaticFiles(directory="static"), name="static")

# 包含路由
app.include_router(api.router, prefix="/api")  # 访问路径会是 /api/exporters/
app.include_router(metrics.router, prefix="/proxy")  # 访问路径会是 /proxy/metrics
app.include_router(views.router)
app.include_router(metrics_router)  # 注意：这会创建一个不带前缀的/metrics路由

@app.on_event("startup")
async def startup():
    """应用启动事件"""
    # 这里可以添加初始化代码，如数据库连接池初始化等
    pass

@app.on_event("shutdown")
async def shutdown():
    """应用关闭事件"""
    # 这里可以添加清理代码，如关闭数据库连接等
    pass

def configure_logging(log_file: str = None):
    """配置日志格式"""
    config = {
        "version": 1,
        "disable_existing_loggers": False,
        "formatters": {
            "default": {
                "()": "uvicorn.logging.DefaultFormatter",
                "fmt": "%(asctime)s [%(levelname)s] %(message)s",
                "datefmt": "%Y-%m-%d %H:%M:%S",
                "use_colors": True,
            },
            "access": {
                "()": "uvicorn.logging.AccessFormatter",
                "fmt": '%(asctime)s [%(levelname)s] %(client_addr)s - "%(request_line)s" %(status_code)s',
                "datefmt": "%Y-%m-%d %H:%M:%S",
            },
        },
        "handlers": {
            "default": {
                "formatter": "default",
                "class": "logging.StreamHandler",
                "stream": "ext://sys.stderr",
            },
            "access": {
                "formatter": "access",
                "class": "logging.StreamHandler",
                "stream": "ext://sys.stdout",
            }
        },
        "loggers": {
            "uvicorn": {"handlers": ["default"], "level": "INFO", "propagate": False},
            "uvicorn.error": {"level": "INFO", "handlers": ["default"], "propagate": False},
            "uvicorn.access": {"handlers": ["access"], "level": "INFO", "propagate": False},
        },
    }
    if log_file:
        # 添加文件处理器
        config["handlers"]["file"] = {
            "class": "logging.handlers.RotatingFileHandler",
            "formatter": "default",
            "filename": log_file,
            "maxBytes": 10 * 1024 * 1024,  # 10MB
            "backupCount": 5,
            "encoding": "utf8",
        }
        
        
        # 将文件处理器添加到日志记录器
        config["loggers"]["uvicorn"]["handlers"].append("file")
        config["loggers"]["uvicorn.error"]["handlers"].append("file")
        config["loggers"]["uvicorn.access"]["handlers"].append("file")
    
    return config

if __name__ == "__main__":
    # 修正了错误的模块路径 "app:mian:app" 应该是 "app.main:app"
    uvicorn.run(
        "main:app",
        host=settings.server_host,
        port=settings.server_port,
        reload=settings.debug,  # 仅在调试模式下启用热重载
        log_config=configure_logging(
            log_file=settings.log_file
        ),
        access_log=True,  # 启用访问日志
    )